package com.ruoyi.product.service.impl;

import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.constant.HttpStatus;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.product.es.EsProd;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import com.ruoyi.product.mapper.TbProdMapper;
import com.ruoyi.product.domain.TbProd;
import com.ruoyi.product.service.ITbProdService;

/**
 * 商品管理Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-08-08
 */
@Service
public class TbProdServiceImpl implements ITbProdService 
{
    @Autowired
    private TbProdMapper tbProdMapper;
    @Autowired
    ElasticsearchRestTemplate elasticsearchRestTemplate;

    /**
     * 查询商品管理
     * 
     * @param prodId 商品管理主键
     * @return 商品管理
     */
    @Override
    public TbProd selectTbProdByProdId(Long prodId)
    {
        return tbProdMapper.selectTbProdByProdId(prodId);
    }

    /**
     * 查询商品管理列表
     * 
     * @param tbProd 商品管理
     * @return 商品管理
     */
    @Override
    public List<TbProd> selectTbProdList(TbProd tbProd)
    {
        return tbProdMapper.selectTbProdList(tbProd);
    }

    /**
     * 新增商品管理
     * 
     * @param tbProd 商品管理
     * @return 结果
     */
    @Override
    public int insertTbProd(TbProd tbProd)
    {
        tbProd.setCreateTime(DateUtils.getNowDate());
        return tbProdMapper.insertTbProd(tbProd);
    }

    /**
     * 修改商品管理
     * 
     * @param tbProd 商品管理
     * @return 结果
     */
    @Override
    public int updateTbProd(TbProd tbProd)
    {
        tbProd.setUpdateTime(DateUtils.getNowDate());
        return tbProdMapper.updateTbProd(tbProd);
    }

    /**
     * 批量删除商品管理
     * 
     * @param prodIds 需要删除的商品管理主键
     * @return 结果
     */
    @Override
    public int deleteTbProdByProdIds(Long[] prodIds)
    {
        return tbProdMapper.deleteTbProdByProdIds(prodIds);
    }

    /**
     * 删除商品管理信息
     * 
     * @param prodId 商品管理主键
     * @return 结果
     */
    @Override
    public int deleteTbProdByProdId(Long prodId)
    {
        return tbProdMapper.deleteTbProdByProdId(prodId);
    }

    @Override
    public AjaxResult createProdIndex() {
        IndexOperations indexOps = elasticsearchRestTemplate.indexOps(EsProd.class);
        boolean exists = indexOps.exists();
        if(exists){
            //如果存在则删除
            indexOps.delete();
        }
        indexOps.create();

        Document mapping = indexOps.createMapping();
        indexOps.putMapping(mapping);

        return AjaxResult.success("索引创建成功");
    }

    @Override
    public AjaxResult syncProdIndex() {
        List<TbProd> tbProds = tbProdMapper.selectTbProdList(new TbProd());

        for (TbProd tbProd : tbProds) {
            EsProd esProd = BeanUtil.toBean(tbProd, EsProd.class);

            elasticsearchRestTemplate.save(esProd);
        }
        return AjaxResult.success("数据同步完成");
    }

    @Override
    public TableDataInfo listFromEs(TbProd tbProd, Integer pageNum, Integer pageSize) {
        Integer form = 0;
        if(pageNum>0){
            pageNum = (pageNum - 1);
        }
        PageRequest pageRequest = PageRequest.of(pageNum, pageSize);

        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        if(StringUtils.isNotEmpty(tbProd.getProdName())){
            boolQueryBuilder.must(QueryBuilders.matchQuery("prodName",tbProd.getProdName()));
        }

        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("prodName").preTags("<font color='red'>").postTags("</font>");

        FieldSortBuilder sortBuilder = SortBuilders.fieldSort("prodId").order(SortOrder.DESC);

        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        nativeSearchQueryBuilder.withPageable(pageRequest)
                .withQuery(boolQueryBuilder)
                .withHighlightBuilder(highlightBuilder)
                .withSorts(sortBuilder);

        SearchHits<EsProd> searchHits = elasticsearchRestTemplate.search(nativeSearchQueryBuilder.build(), EsProd.class);

        ArrayList<EsProd> list = new ArrayList<>();

        for (SearchHit<EsProd> searchHit : searchHits) {
            EsProd esProd = searchHit.getContent();

            List<String> prodNameList = searchHit.getHighlightField("prodName");
            if(prodNameList!=null&&prodNameList.size()>0){
                esProd.setProdName(prodNameList.get(0));
            }

            list.add(esProd);
        }

        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setRows(list);
        rspData.setMsg("查询成功");
        rspData.setTotal(searchHits.getTotalHits());
        return rspData;
    }
}
